<?php
/**
 * Created by PhpStorm.
 * User: iceberg
 * Date: 2018-10-10
 * Time: 16:40
 */

namespace app\base\controller;


use think\Controller;
use think\Db;

class Test extends Controller
{
    public function batchAdd()
    {
        $arrays = ['肉禽腌肉类', '蔬菜类', '水产类', '豆制品腌菜类', '粮油调料类'];
        foreach ($arrays as $val){

            echo $val;
            $category = new \app\model\Category();
            $category->save([
                'pid'  =>  0,
                'name' =>  $val,
                'status' => 1,
                'desc'  => '',
            ]);
        }

        echo 'ok';

    }

    public function getCategory()
    {
        $list = \app\model\Category::column('id','name');
        return json_encode($list);
    }

    public function wirteJson(){
        $dataInfo = Db::query("select id as v,name as n,pid from st_category");
        $data = $this->getCategoryJson($dataInfo);
        return $data;
    }

    function generateTree($items) {
        $tree = array();
        foreach($items as $item){
            if(isset($items[$item['pid']])){
                $items[$item['pid']]['s'][] = &$items[$item['v']];
            }else{
                $tree[] = &$items[$item['v']];
            }
        }
        return $tree;
    }

    public function getCategoryJson($dataInfo) {
        /*生成json数据*/
        foreach($dataInfo as $category) {
            $tree[$category['v']] = $category;
            $tree[$category['v']]['s'] = array();
        }
        $content = json_encode($this->generateTree($tree));
        $content = str_replace(',"s":[]', "", $content);
        // for( $i = 0; $i < count($dataInfo); $i++ ) {
        //     $content = str_replace('"'.$dataInfo[$i]['v'].'":', "", $content);
        // }
        //$content = '['.substr($content,1,strlen($content)-2).']';
        //return $content;
        /*写入文件*/
        //文件存放路径
        $filePath = $_SERVER['DOCUMENT_ROOT'].'/category.json';
        $returnval = file_put_contents($filePath,$content);
        // $fopen = fopen($filePath,'w+');
        // fwrite($fopen,$content);
        // fclose($fopen);
        return $returnval;
    }
}